/**
 * 飞书API工具
 * 封装飞书开放平台相关API调用
 */

const config = require("../config/environment");
const axios = require("axios");
const logger = require("./logger");

/**
 * 生成登录页面的URL
 * @returns {string} 登录页面URL
 */
const startLoginPageUrl = () => {
  return `https://open.feishu.cn/open-apis/authen/v1/index?` +
    `app_id=${config.feishu.appId}&` +
    `redirect_uri=${encodeURIComponent(config.feishu.redirectUri)}`;
};

/**
 * 获取app_access_token
 * @returns {Promise<string>} app_access_token
 */
const getAppAccessToken = async () => {
  try {
    const response = await axios.post(
      "https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal",
      {
        app_id: config.feishu.appId,
        app_secret: config.feishu.appSecret,
      },
      {
        headers: {
          "Content-Type": "application/json; charset=utf-8",
        },
      }
    );

    if (response.data && response.data.app_access_token) {
      return response.data.app_access_token;
    }

    throw new Error("获取 app_access_token 失败: " + JSON.stringify(response.data));
  } catch (error) {
    logger.error("获取 App Access Token 异常", error.response?.data || error.message);
    throw new Error("Failed to get App Access Token");
  }
};

/**
 * 获取user_access_token
 * @param {string} code - 授权码
 * @returns {Promise<Object>} token信息对象
 */
const getUserAccessToken = async (code) => {
  try {
    const appAccessToken = await getAppAccessToken();
    const response = await axios.post(
      "https://open.feishu.cn/open-apis/authen/v1/access_token",
      {
        grant_type: "authorization_code",
        code: code,
      },
      {
        headers: {
          "Content-Type": "application/json; charset=utf-8",
          Authorization: `Bearer ${appAccessToken}`,
        },
      }
    );

    if (response.data && response.data.data && response.data.data.access_token) {
      return response.data.data;
    }

    throw new Error("获取 user_access_token 失败: " + JSON.stringify(response.data));
  } catch (error) {
    logger.error("获取 User Access Token 异常", error.response?.data || error.message);
    throw new Error("Failed to get User Access Token");
  }
};

/**
 * 刷新user_access_token
 * @param {string} refreshToken - 刷新token
 * @returns {Promise<Object>} 新的token信息对象
 */
const refreshUserAccessToken = async (refreshToken) => {
  try {
    const appAccessToken = await getAppAccessToken();
    const response = await axios.post(
      "https://open.feishu.cn/open-apis/authen/v1/refresh_access_token",
      {
        grant_type: "refresh_token",
        refresh_token: refreshToken,
      },
      {
        headers: {
          "Content-Type": "application/json; charset=utf-8",
          Authorization: `Bearer ${appAccessToken}`,
        },
      }
    );

    if (response.data && response.data.data && response.data.data.access_token) {
      return response.data.data;
    }

    throw new Error("刷新 user_access_token 失败: " + JSON.stringify(response.data));
  } catch (error) {
    logger.error("刷新 User Access Token 异常", error.response?.data || error.message);
    throw new Error("Failed to refresh User Access Token");
  }
};

/**
 * 获取用户信息
 * @param {string} accessToken - 用户access_token
 * @returns {Promise<Object>} 用户信息对象
 */
const getUserInfo = async (accessToken) => {
  try {
    const response = await axios.get(
      "https://open.feishu.cn/open-apis/authen/v1/user_info",
      {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      }
    );

    if (response.data && response.data.data) {
      return response.data.data;
    }

    throw new Error("获取用户信息失败: " + JSON.stringify(response.data));
  } catch (error) {
    logger.error("获取用户信息异常", error.response?.data || error.message);
    throw error;
  }
};

module.exports = {
  startLoginPageUrl,
  getAppAccessToken,
  getUserAccessToken,
  refreshUserAccessToken,
  getUserInfo,
};
